# Create your views here.
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext 
from lab.blog.models import Post, Tag, PostForm, TagForm
from django.template import defaultfilters

def post_form(request, slug=None):
    post = None
    if slug is not None:
        post = Post.objects.get(slug=slug)
    if request.POST:
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.slug = defaultfilters.slugify(new_post.title)
            new_post.author = request.user
            new_post.save()
            form.save_m2m()
            return HttpResponseRedirect('/blog/')
    else:
        form = PostForm(instance=post)
        
    return render_to_response('blog/post_form.html',{'form':form},context_instance=RequestContext(request))

def tag_form(request, slug=None):
    tag = None
    if slug is not None:
        tag = Tag.objects.get(slug=slug)
    if request.POST:
        form = TagForm(data=request.POST, instance=tag)
        if form.is_valid():
	        new_tag = form.save(commit=False)
        	new_tag.slug = defaultfilters.slugify(new_tag.title)
            	new_tag.creator = request.user
       	 	new_tag.save()
        #	form.save_m2m()
        	return HttpResponseRedirect('/blog/')
    else:
        form = TagForm(instance = tag)
        
    return render_to_response('blog/tag_form.html',{'form':form},context_instance=RequestContext(request))

def public_list(request):
    public = Post.objects.filter(is_public=True).order_by('create_date')[0:2]
    return render_to_response('blog/public_list.html',{'public_list':public}, context_instance=RequestContext(request))